﻿using AutoMapper;
using B.S.AuthCenter.Api.Read.Application.Command.MenuRole;
using B.S.AuthCenter.Api.Read.DTOs.RoleMenu;
using B.S.AuthCenter.Domain;
using B.S.AuthCenter.ErrorCount;
using B.S.AuthCenter.InfrasIntructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.AuthCenter.Api.Read.Application.Handler.MenuRole
{
    public class GetRoleMenuHandler : IRequestHandler<GetRoleMenuCommand, ApiResult<List<RoleMenuDTO>>>
    {
        IBaseRepository<RoleMenuModel> roleMenuRepo;
        IBaseRepository<MenuManageModel> menuRepo;
        IMapper mapper;

        public GetRoleMenuHandler(IBaseRepository<RoleMenuModel> roleMenuRepo, IBaseRepository<MenuManageModel> menuRepo, IMapper mapper)
        {
            this.roleMenuRepo = roleMenuRepo;
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }

        public Task<ApiResult<List<RoleMenuDTO>>> Handle(GetRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<RoleMenuDTO>> res=new ApiResult<List<RoleMenuDTO>>();
            var list=roleMenuRepo.GetAll().Where(c=>c.Rid==request.Rid && !c.IsDeleted);
            var model=mapper.Map<List<RoleMenuDTO>> (list);
            foreach (var item in model)
            {
                item.MenuName = menuRepo.GetAll().Where(c => c.Id == item.Mid).FirstOrDefault().MenuName;
            }
            res.Code = ApiEnum.Success;
            res.Msg = "查询角色分配权限成功";
            res.Datas = model;
            return Task.FromResult(res);
        }
    }
}
